import express, {
    query
} from "express"
import path, { parse } from "path"
import fs from "fs"
import uuid from "node-uuid"
let staticUrl = path.join(__dirname, "./public")
let app = express()
app.listen(3000, () => {
    console.log("服务器启动了");
})
//登录拦截
app.get("/hom.html", (req, res, next) => {
    //获取 登陆凭证
    let str = req.get("Cookie") || ""
    //转数组

    let arr = str.split("; ")
    //转对象
    let obj = {}
    arr.forEach(item => {
        obj[item.slice(0, item.indexOf("="))] = item.slice(item.indexOf("=") + 1)
    })
    //拿到登录凭证
    let loginStr = obj["cook"] || null
    console.log(123);
    console.log(loginStr);
    //获取服务器存放的凭证文件

    let brr = fs.readFileSync(path.join("./public/cook.json"), "utf-8")
    console.log(brr);
    brr = JSON.parse(brr)
    //查找凭证是否存在
    let is = brr.find(item => {
        return item === loginStr
    })
    if (is) { //凭证存在 用户已经登录 next 走静态资源访问
        next()
    } else { //凭证不存在 重定向到登录页面
        res.redirect("./login.html")
    }
})
//访问静态资源
app.use(
    express.static(staticUrl)

)
//处理get请求
app.get("/login", (req, res, next) => {
    let {
        user,
        pass
    } = req.query
    //获取 服务器存放的user 文件
    let arr = JSON.parse(fs.readFileSync(path.join(__dirname, "./public/user.json")))
    //查找
    let is = arr.find(item => {
        return item.user === user
    })
    if (is) {
        if (is.pass === pass) {
            let id = uuid.v1()
            let brr = JSON.parse(fs.readFileSync(path.join(__dirname,"./public/cook.json")),"utf-8")
            brr.push(id)
            fs.writeFileSync(path.join(__dirname,"./public/cook.json"),JSON.stringify(brr),"utf-8")
            res.cookie("cook",id)
            res.send("001")
        } else {
            res.send("002")
        }
    } else {
        res.send("003")
    }
})
//获取post请求参数
app.use(
    express.json()
)

//处理post请求
app.post("/login", (req, res, next) => {
    let body = req.body
})